// Copyright Project Harbor Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package vulnerability

import (
	"time"

	"github.com/goharbor/harbor/src/common/rbac"
	"github.com/goharbor/harbor/src/jobservice/job"
	"github.com/goharbor/harbor/src/pkg/permission/types"
	"github.com/goharbor/harbor/src/pkg/robot/model"
	scanJob "github.com/goharbor/harbor/src/pkg/scan"
	"github.com/goharbor/harbor/src/pkg/scan/dao/scan"
	"github.com/goharbor/harbor/src/pkg/scan/postprocessors"
	v1 "github.com/goharbor/harbor/src/pkg/scan/rest/v1"
)

func init() {
	scanJob.RegisterScanHanlder(v1.ScanTypeVulnerability, &ScanHandler{})
}

// ScanHandler defines the handler for scan vulnerability
type ScanHandler struct {
}

// RequestProducesMineTypes returns the produces mime types
func (v *ScanHandler) RequestProducesMineTypes() []string {
	return []string{v1.MimeTypeGenericVulnerabilityReport}
}

// RequestParameters defines the parameters for scan request
func (v *ScanHandler) RequestParameters() map[string]interface{} {
	return nil
}

// RequiredPermissions defines the permission used by the scan robot account
func (v *ScanHandler) RequiredPermissions() []*types.Policy {
	return []*types.Policy{
		{
			Resource: rbac.ResourceRepository,
			Action:   rbac.ActionPull,
		},
		{
			Resource: rbac.ResourceRepository,
			Action:   rbac.ActionScannerPull,
		},
	}
}

// ReportURLParameter vulnerability doesn't require any scan report parameters
func (v *ScanHandler) ReportURLParameter(_ *v1.ScanRequest) (string, error) {
	return "", nil
}

// PostScan ...
func (v *ScanHandler) PostScan(ctx job.Context, _ *v1.ScanRequest, origRp *scan.Report, rawReport string, _ time.Time, _ *model.Robot) (string, error) {
	// use a new ormer here to use the short db connection
	_, refreshedReport, err := postprocessors.Converter.ToRelationalSchema(ctx.SystemContext(), origRp.UUID, origRp.RegistrationUUID, origRp.Digest, rawReport)
	return refreshedReport, err
}
